import gc
import vfs
from flashbdev import bdev
import builtins

try:
    if bdev:
        vfs.mount(bdev, "/")
except OSError:
    import inisetup
    inisetup.setup()

# 自动初始化I2C
try:
    from machine import I2C, Pin, UART
    
    # 创建I2C对象 - 使用默认的SDA和SCL引脚
    # ESP32默认: SDA=21, SCL=22
    i2c = I2C(0, sda=Pin(22), scl=Pin(21), freq=100000)
    
    # 扫描I2C设备
    devices = i2c.scan()
    if devices:
        # 根据I2C设备数量判断板卡类型
        if len(devices) == 3 and devices[0] == 0x28 and devices[1] == 0x58 and devices[2] == 0x68:
            board_type = "Weeecore Bot"
        elif len(devices) == 2 and devices[0] == 0x58 and devices[1] == 0x68:
            board_type = "Weeecore"
        elif len(devices) == 1 and devices[0] == 0x58:
            board_type = "大师兄"
        else:
            board_type = "unknown device"
        print(f"Board Type: {board_type}")
    else:
        print("I2C initialization is successful, but no device is found")
        board_type = "No I2C devices found"

    # 创建UART对象
    uart = UART(2, baudrate=9600, tx=Pin(4), rx=Pin(16))
    
    # 初始化AW9523
    try:
        from wm_mod.weeecore.wm_aw9523 import wm_aw9523
        aw = wm_aw9523(i2c=i2c)
        builtins.aw = aw
    except Exception as e:
        print(f"AW9523 initialization failed: {e}")
        aw = None
        
    # 设置全局变量 - 使用最有效的方法
    globals().update({
        'i2c': i2c,
        'uart': uart,
        'BoardType': board_type
    })
    
    # 同时设置到__main__模块以确保可用性
    try:
        __import__('__main__').i2c = i2c
        __import__('__main__').uart = uart
        __import__('__main__').BoardType = board_type
    except:
        pass
    
    print("全局变量设置完成")
    
except Exception as e:
    print(f"I2C initialization failed: {e}")

gc.collect()
